package com.example.demo.service.impl;

import com.example.demo.dto.RoleDepartmentUserDTO;
import com.example.demo.entity.RoleDepartmentUser;
import com.example.demo.mapper.RoleDepartmentUserMapper;
import com.example.demo.request.CreateRoleDepartmentUserRequest;
import com.example.demo.service.RoleDepartmentUserService;
import com.example.demo.service.RoleConfigService;
import com.example.demo.service.DepartmentService;
import com.example.demo.service.UserService;
import com.example.demo.dto.RoleConfigDTO;
import com.example.demo.dto.DepartmentDTO;
import com.example.demo.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleDepartmentUserServiceImpl implements RoleDepartmentUserService {

    @Autowired
    private RoleDepartmentUserMapper roleDepartmentUserMapper;

    @Autowired
    private RoleConfigService roleConfigService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserService userService;

    @Override
    public List<RoleDepartmentUserDTO> getRoleDepartmentUsers(int page, int size) {
        List<RoleDepartmentUser> roleDepartmentUsers = roleDepartmentUserMapper.selectAll();
        return roleDepartmentUsers.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public long countRoleDepartmentUsers() {
        return roleDepartmentUserMapper.count();
    }

    @Override
    public RoleDepartmentUserDTO getRoleDepartmentUserById(Integer id) {
        RoleDepartmentUser roleDepartmentUser = roleDepartmentUserMapper.selectById(id);
        return convertToDTO(roleDepartmentUser);
    }

    @Override
    public RoleDepartmentUser createRoleDepartmentUser(CreateRoleDepartmentUserRequest request) {
        RoleDepartmentUser roleDepartmentUser = new RoleDepartmentUser();
        roleDepartmentUser.setRoleConfigId(request.getRoleConfigId());
        roleDepartmentUser.setDepartmentId(request.getDepartmentId());
        roleDepartmentUser.setUserId(request.getUserId());
        roleDepartmentUser.setIsDefault(request.getIsDefault());

        // 自动填充冗余字段
        populateRedundantFields(roleDepartmentUser);

        roleDepartmentUserMapper.insert(roleDepartmentUser);
        return roleDepartmentUser;
    }

    @Override
    public void updateRoleDepartmentUser(Integer id, CreateRoleDepartmentUserRequest request) {
        RoleDepartmentUser roleDepartmentUser = roleDepartmentUserMapper.selectById(id);
        roleDepartmentUser.setRoleConfigId(request.getRoleConfigId());
        roleDepartmentUser.setDepartmentId(request.getDepartmentId());
        roleDepartmentUser.setUserId(request.getUserId());
        roleDepartmentUser.setIsDefault(request.getIsDefault());

        // 自动填充冗余字段
        populateRedundantFields(roleDepartmentUser);

        roleDepartmentUserMapper.updateById(roleDepartmentUser);
    }

    @Override
    public void deleteRoleDepartmentUser(Integer id) {
        roleDepartmentUserMapper.deleteById(id);
    }

    @Override
    public List<RoleDepartmentUserDTO> searchByRoleName(String roleName) {
        List<RoleDepartmentUser> roleDepartmentUsers = roleDepartmentUserMapper.selectByRoleNameLike(roleName);
        return roleDepartmentUsers.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<RoleDepartmentUserDTO> searchByDepartmentName(String departmentName) {
        List<RoleDepartmentUser> roleDepartmentUsers = roleDepartmentUserMapper.selectByDepartmentNameLike(departmentName);
        return roleDepartmentUsers.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<RoleDepartmentUserDTO> searchByUserName(String userName) {
        List<RoleDepartmentUser> roleDepartmentUsers = roleDepartmentUserMapper.selectByUserNameLike(userName);
        return roleDepartmentUsers.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private RoleDepartmentUserDTO convertToDTO(RoleDepartmentUser roleDepartmentUser) {
        // 获取角色配置名称
        String roleConfigName = null;
        if (roleDepartmentUser.getRoleConfigId() != null) {
            try {
                RoleConfigDTO roleConfig = roleConfigService.getRoleConfigById(roleDepartmentUser.getRoleConfigId());
                roleConfigName = roleConfig != null ? roleConfig.getRoleName() : null;
            } catch (Exception e) {
                // 如果查询失败，保持为null
                roleConfigName = null;
            }
        }

        // 获取部门名称
        String departmentName = null;
        if (roleDepartmentUser.getDepartmentId() != null) {
            try {
                DepartmentDTO department = departmentService.getDepartmentById(roleDepartmentUser.getDepartmentId());
                departmentName = department != null ? department.getDeptName() : null;
            } catch (Exception e) {
                // 如果查询失败，保持为null
                departmentName = null;
            }
        }

        // 获取用户名称
        String userName = null;
        if (roleDepartmentUser.getUserId() != null) {
            try {
                UserDTO user = userService.getUserById(roleDepartmentUser.getUserId());
                userName = user != null ? user.getUserName() : null;
            } catch (Exception e) {
                // 如果查询失败，保持为null
                userName = null;
            }
        }

        return RoleDepartmentUserDTO.fromEntityWithNames(roleDepartmentUser, roleConfigName, departmentName, userName);
    }

    /**
     * 自动填充冗余字段
     */
    private void populateRedundantFields(RoleDepartmentUser roleDepartmentUser) {
        // 填充角色名称
        if (roleDepartmentUser.getRoleConfigId() != null) {
            try {
                RoleConfigDTO roleConfig = roleConfigService.getRoleConfigById(roleDepartmentUser.getRoleConfigId());
                roleDepartmentUser.setRoleName(roleConfig != null ? roleConfig.getRoleName() : null);
            } catch (Exception e) {
                roleDepartmentUser.setRoleName(null);
            }
        }

        // 填充部门名称
        if (roleDepartmentUser.getDepartmentId() != null) {
            try {
                DepartmentDTO department = departmentService.getDepartmentById(roleDepartmentUser.getDepartmentId());
                roleDepartmentUser.setDepartmentName(department != null ? department.getDeptName() : null);
            } catch (Exception e) {
                roleDepartmentUser.setDepartmentName(null);
            }
        }

        // 填充用户名称和用户认证ID
        if (roleDepartmentUser.getUserId() != null) {
            try {
                UserDTO user = userService.getUserById(roleDepartmentUser.getUserId());
                if (user != null) {
                    roleDepartmentUser.setUserName(user.getUserName());
                    roleDepartmentUser.setUserAuthid(user.getAuthId());
                } else {
                    roleDepartmentUser.setUserName(null);
                    roleDepartmentUser.setUserAuthid(null);
                }
            } catch (Exception e) {
                roleDepartmentUser.setUserName(null);
                roleDepartmentUser.setUserAuthid(null);
            }
        }
    }
}